import time

from dbutils.pooled_db import PooledDB
from urllib.parse import quote
import pymysql
import copy
import redis


# Redis_ip = '192.168.14.93'
Redis_ip = '192.168.14.93'
Redis_password = ''
Redis_port = 6379

# 数据库连接池
pool = PooledDB(pymysql, maxconnections=10, host=Redis_ip, user='root', password='abc123',
                database='seal_system',
                read_timeout=30,  # 读取超时设置
                write_timeout=30,  # 写入超时设置
                charset='utf8')

# 获取视频为录像机子集的返回格式  参数为  父级id  子集通道code
def get_children_rtsp(id, code, type):
    # 从连接池获取连接对象
    conn = pool.connection()
    cursor = conn.cursor()
    try:

        sql = "SELECT equipment_uname, equipment_password, equipment_ip FROM t_equipment WHERE id = %s"
        cursor.execute(sql, (id,))
        parent_data = cursor.fetchone()
        if parent_data:
            user = parent_data[0]
            password = parent_data[1]
            ip = parent_data[2]

            # 录像机
            if type == 1:

                result = 'rtsp://{}:{}@{}:554/Streaming/Unicast/Channels/{}'.format(quote(user), quote(password), quote(ip), code)

            # 特殊摄像头 海康双目
            else:
                result = 'rtsp://{}:{}@{}:554/Streaming/Channels/{}'.format(quote(user), quote(password), quote(ip), code)
        else:
            result = None
    finally:
        conn.close()

    return result


# 转换成袁总格式数据
def convert_data_format(res):
    result = []
    for group in res:
        if not group:
            continue
        common_type = group[0]['type']
        # 使用列表推导式删除 'type' 键
        data_without_type = [{k: v for k, v in item.items() if k != 'type' and  k != 'color'} for item in group]
        data = {'type': common_type, 'data': data_without_type}
        result.append([data])
    return result


# 获取所需数据
def get_data():
    # 从连接池获取连接对象
    conn = pool.connection()
    cursor = conn.cursor()

    sql = (
        "SELECT c.id AS Mine_id, c.mine_name, d.id AS Equipment_id, "
        "d.equipment_name, d.equipment_type, d.equipment_ip, d.equipment_uname, d.equipment_password, "
        "d.code, d.parent_id, d.Hik_rtsp_url, "
        "a.id AS Conf_id, a.Algorithm_library_id, a.conf_area, e.id AS test_type_id, e.test_type_ename, "
        "b.algorithm_status, b.algorithm_path, b.algorithm_name, b.algorithm_type_list, b.algorithm_trade_type, "
        "a.status, a.conf_name,a.shield_status, a.tem_conf_area, a.draw_type, a.confidence, a.interval_time, "
        "a.duration_time, a.image_draw_type, a.scene_typename, a.sensitivity,a.image_count,a.template_list_area,"
        "a.computing_id,a.template_data,a.conf_status,a.res_type,a.template_small_id,h.template_small_name,a.model_status,   "
        "f.dev_id, g.model_name AS template_name, g.model_type AS template_type,g.model_template_config_type_id as template_config_type_id,"
        "a.label_list,conf_img_resolution,defense_time_start,defense_time_end, "
        "g.model_conf_list AS template_model_conf_list,g.id as template_id,h.list_data "
        "FROM `t_algorithm_config` AS a "
        "JOIN `t_algorithm_library` AS b ON a.Algorithm_library_id = b.id "
        "JOIN `t_mine` AS c ON a.Mine_id = c.id "
        "JOIN `t_equipment` AS d ON a.Equipment_id = d.id "
        "JOIN `t_algorithm_test_type` AS e ON a.Algorithm_test_type_id = e.id "
        "JOIN `t_resource_usage` AS f ON a.resource_id = f.id "
        "JOIN `t_model_template_config` AS g ON a.model_template_config_id = g.id "
        "JOIN `t_model_template_small` AS h ON a.template_small_id = h.id "
        # "WHERE b.algorithm_status = 1 AND a.status = 1 AND b.algorithm_trade_type = 2 AND a.computing_id=2;"
        "WHERE b.algorithm_status = 1 AND a.status = 1 AND b.algorithm_trade_type = 2 ;"
    )

    cursor.execute(sql)

    # 获取查询结果集的列名
    columns = [i[0] for i in cursor.description]

    results = cursor.fetchall()

    # 构建字典列表
    result_dict_list = [dict(zip(columns, i)) for i in results]


    # 在列表推导式中使用了浅拷贝 copy.deepcopy() 来复制每个字典，更新 'rtsp_url' 字段。
    # 这样做可以保留原始数据的所有字段，同时只对 'rtsp_url' 进行修改。
    # 更新每个字典的 'rtsp_url' 和 'conf_area' 字段
    updated_result_dict_list = []

    # for i in result_dict_list:
    #     updated_dict = copy.deepcopy(i)
    #     updated_dict['conf_area'] = convert_data_format(eval(i['conf_area']))
    #     updated_dict['template_list_area'] =convert_data_format(eval(i['template_list_area'])) if i.get('template_list_area')  else []
    #
    #     if i['equipment_type'] == '摄像头':
    #         updated_dict['rtsp_url'] = 'rtsp://{}:{}@{}'.format(quote(i['equipment_uname']), quote(i['equipment_password']),
    #                                                             quote(i['equipment_ip']))
    #     elif i['equipment_type'] == '特殊摄像头':
    #         updated_dict['rtsp_url'] = get_children_rtsp(i['parent_id'], i['code'], 2)
    #     elif i['equipment_type'] == '录像机':
    #         updated_dict['rtsp_url'] = get_children_rtsp(i['parent_id'], i['code'], 1)
    #     elif i['equipment_type'] == '浙江双视热成像':
    #         updated_dict['rtsp_url'] = 'rtsp://{}:{}@{}:554/live/chn0'.format(quote(i['equipment_uname']),
    #                                                                           quote(i['equipment_password']),
    #                                                                           quote(i['equipment_ip']))
    #     elif i['equipment_type'] == '安防平台':
    #         updated_dict['rtsp_url']=quote(i['Hik_rtsp_url'])
    #
    #     updated_result_dict_list.append(updated_dict)
    #
    # # 更新后的 result_dict_list
    # result_dict_list = updated_result_dict_list
    #
    # return result_dict_list


# print(get_data())

# redus 队列
class Redis_Template_key:
    def __init__(self):
        self.r = redis.Redis(host=Redis_ip, port=Redis_port,password=Redis_password,decode_responses=True)

    # 查找算法配置id及对应key,监听，当key为0的时候进行对应数据项重启
    # 获取id对应key进行配置归0
    def set_id_key(self, id):
        # 修正格式化问题
        return self.r.set('{}_key'.format(id), 0)

    def get_id_key(self, id):
        return self.r.get('{}_key'.format(id))



while 1:
    time.sleep(5)
    print(get_data())
# list = [i for i in get_data() if i.get('template_name') == '行车不行人检测']
# print(list,len(list))
# for i in get_data():
#     print(i)
#
#     # print(i.get('template_name'),i.get('Conf_id'),i.get('rtsp_url'),i.get('algorithm_path'))
#     if i.get('template_name') == '通用模型物体检测':
#         print(i,'111')
#     else:
#         pass

    # tem_key = r.get_id_key(i.get('Conf_id'))
    # print(tem_key)
    # if tem_key == '0':
    #     print(i.get('Conf_id'),i.get('template_name'),i.get('Equipment_id'),'数据配置id,对应数据路径')


# print(get_data())



